import axios, { AxiosResponse } from 'axios';

const request = axios.create({
    baseURL: '/api',
});


// 添加请求拦截器
request.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(function (response:AxiosResponse) {
    return response;
  }, function (error) {
    return Promise.reject(error);
});

const http = {
    get<T>( url:string, params?:any  ):Promise<T>{
        return new Promise((resolve,reject)=>{
            request
                .get<T>(url,{params})
                .then((res:AxiosResponse<T>) =>{
                    resolve( res.data );
                })
                .catch((error)=>{
                    reject(error)
                })
        })
    },
    post<T>( url:string, data?:any  ):Promise<T>{
        return new Promise((resolve,reject)=>{
            request
                .post<T>(url,data)
                .then((res:AxiosResponse<T>) =>{
                    resolve( res.data );
                })
                .catch((error)=>{
                    reject(error)
                })
        })
    }
}

export default http;
